package org.lifei.org.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.lifei.auth.dto.LoginDTO;
import org.lifei.org.domain.Employee;
import org.lifei.org.mapper.EmployeeMapper;
import org.lifei.org.query.EmployeeQuery;
import org.lifei.org.service.IEmployeeService;
import org.lifei.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lifei
 * @since 2024-01-17
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Employee selectByUsername(LoginDTO loginDTO) {
        return employeeMapper.selectByUsername(loginDTO);
    }

    @Override
    public void download(List<Employee> employees, OutputStream outputStream ) throws Exception {
        Workbook workbook = null;
        try {
            System.out.println(employeeMapper.querydown());

            List<Employee> employees1 = employeeMapper.queryAll();
            employees1.forEach(System.out::println);
            workbook = ExcelExportUtil.exportExcel(new ExportParams(), Employee.class, employees1);
            workbook.write(outputStream);
        } finally {
            try {
                Objects.requireNonNull(workbook).close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public List<Employee> upload(MultipartFile file) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setNeedVerify(true);//开启校验
//        System.out.println(file.getSize());
        //importExcelMore()相比于importExcel()
        ExcelImportResult<Employee> result = ExcelImportUtil.importExcelMore(file.getInputStream(), Employee.class, importParams);

        System.out.println("=============将要保存的数据=============");
//        result.getList().forEach(System.out::println);
        employeeMapper.batchInsert(result.getList());

        return result.getFailList();
    }

    @Override
    public List<Employee> selectByKey(EmployeeQuery employeeQuery) {
        return employeeMapper.selectByKey(employeeQuery);
    }

    @Override
    public List<String> selectPermissionSnsById(Long id) {
        return employeeMapper.selectPermissionSnsById(id);
    }
}
